package com.yeskery.nut.bean.condition;

import com.yeskery.nut.annotation.condition.ConditionalOnJava;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.core.JavaVersion;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java版本条件判断
 * @author sunjay
 * 2023/9/6
 */
public class OnJavaCondition implements Condition {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(OnJavaCondition.class.getName());

    @Override
    public boolean matches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata, Object conditionalAnnotation) {
        ConditionalOnJava conditionalOnJava = (ConditionalOnJava) conditionalAnnotation;
        JavaVersion javaVersion = JavaVersion.getJavaVersion();
        if (ConditionalOnJava.Range.EQUAL_OR_NEWER == conditionalOnJava.range()) {
            boolean result = javaVersion.isEqualOrNewerThan(conditionalOnJava.value());
            if (!result && logger.isLoggable(Level.FINEST)) {
                logger.log(Level.FINEST, "Java Version Condition Not Match, Condition[" + this.getClass().getName()
                        + "], Expect Java Version Equal Or Newer[" + conditionalOnJava.value().name()
                        + "], Actual Java Version[" + javaVersion.name() + "].");
            }
            return result;
        } else if (ConditionalOnJava.Range.OLDER_THAN == conditionalOnJava.range()) {
            boolean result = javaVersion.isOlderThan(conditionalOnJava.value());
            if (!result && logger.isLoggable(Level.FINEST)) {
                logger.log(Level.FINEST, "Java Version Condition Not Match, Condition[" + this.getClass().getName()
                        + "], Expect Java Version Older Than[" + conditionalOnJava.value().name()
                        + "], Actual Java Version[" + javaVersion.name() + "].");
            }
            return result;
        } else {
            throw new NutException("Unknown JavaVersion Enum.");
        }
    }
}
